//
//  YXMyInfoViewController.m
//  跑跑快销
//
//  Created by 杨潇 on 14-4-29.
//  Copyright (c) 2014年 ylife. All rights reserved.
//

#import "YXMyInfoViewController.h"
#import "YXPersonMessageTableViewCell.h"
#import "YXAmendMessageViewController.h"
#import "YXAmendPasswordViewController.h"
#import "YXLoginViewController.h"
#import "YXChangeCodeViewController.h"
#import "YXSetViewController.h"

@interface YXMyInfoViewController ()

@end

@implementation YXMyInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    UIButton * setBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    [setBtn setBackgroundImage:[UIImage imageNamed:@"跑车.jpg"] forState:UIControlStateNormal];
    [setBtn addTarget:self action:@selector(touchSetBtn) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * setBtnItem = [[UIBarButtonItem alloc] initWithCustomView:setBtn];
    self.navigationItem.rightBarButtonItem = setBtnItem;
    
    YXMyInfoView * myInfoView = [[YXMyInfoView alloc] init];
    self.view = myInfoView;
    _myInfoView = myInfoView;
    
    _myInfoView.tableView.delegate = self;
    _myInfoView.tableView.dataSource = self;
    
    NSArray * titleArr[3];
    titleArr[0] = [NSArray arrayWithObjects:@"",@"性别",@"签名", nil];
    titleArr[1] = [NSArray arrayWithObjects:@"公司",@"行业", nil];
    titleArr[2] = [NSArray arrayWithObjects:@"修改密码",@"切换账户",@"更换激活码", nil];
    _titleArr = [[NSArray alloc] initWithObjects:titleArr[0],titleArr[1],titleArr[2], nil];
    
    _tradeArr = [[NSArray alloc] initWithObjects:@"烟酒类",@"饮品",@"乳制品",@"调味品",@"粮油类",@"冷冻食品类",@"方便食品类",@"休闲食品类",@"保健品类",@"家居日用品类",@"化妆品类",@"服帽类",@"玩具类",@"办公用品类",@"其他(其他行业)", nil];
    
    NSDictionary * infoDic = [[YXWindowInfo sharedWindowInfo] userInfoDic];
    _mutInfoDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[[infoDic objectForKey:@"userInfo"] objectForKey:@"AccountName"],@"AccountName",[[infoDic objectForKey:@"userInfo"] objectForKey:@"AccountSex"],@"AccountSex",[infoDic objectForKey:@"CompanyName"],@"CompanyName",[[infoDic objectForKey:@"userInfo"] objectForKey:@"ProfessionalID"],@"ProfessionalID",[[infoDic objectForKey:@"userInfo"] objectForKey:@"AccountRemark"],@"AccountRemark", nil];
    if ([[_mutInfoDic objectForKey:@"AccountSex"] isEqualToString:@"0"]) {
        userSex[0] = YES;
        userSex[1] = NO;
    }else{
        userSex[0] = NO;
        userSex[1] = YES;
    }
    _professionalsArr = [[NSArray alloc] initWithObjects:@"烟酒类",@"饮品",@"乳制品",@"调味品",@"粮油类",@"冷冻食品类",@"方便食品类",@"休闲食品类",@"保健品类",@"家居日用品类",@"化妆品类",@"服帽类",@"玩具类",@"办公用品类",@"其他(其他行业)", nil];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 10010) {
        return 44;
    }else{
        if (indexPath.section == 0 && indexPath.row == 0) {
            CGSize size = [[_mutInfoDic objectForKey:@"AccountName"] sizeWithFont:[UIFont systemFontOfSize:15]];
            float nameH;
            if (size.width > 160) {
                nameH = (size.width/160+2)*20;
            }
            if (nameH < 85) {
                return 85;
            }
            return (size.width/160+2)*20;
        }else if (indexPath.section == 1 && indexPath.row == 0){
            CGSize size = [[_mutInfoDic objectForKey:@"CompanyName"] sizeWithFont:[UIFont systemFontOfSize:15]];
            if (size.width > 160) {
                return (size.width/160+2)*20;
            }
        }else if (indexPath.section == 0 && indexPath.row == 2){
            CGSize size = [[_mutInfoDic objectForKey:@"AccountRemark"] sizeWithFont:[UIFont systemFontOfSize:15]];
            if (size.width > 160) {
                return (size.width/160+2)*20;
            }
        }
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView.tag == 10010) {
        int trade = [[_mutInfoDic objectForKey:@"ProfessionalID"] intValue];
        if (trade == indexPath.row) {
            _tabBackBtn.hidden = YES;
            return;
        }
        YXWindowInfo * windowInfo = [YXWindowInfo sharedWindowInfo];
        [NSURLConnection sendRequestWithHeadStr:windowInfo.requestUrlStr headValue:[windowInfo.userInfoDic objectForKey:@"token"] serviceToken:nil text:[NSDictionary dictionaryWithObjectsAndKeys:@"updateUserInfo",@"type",@"2",@"editType",[NSString stringWithFormat:@"%d",indexPath.row],@"parameter",[[windowInfo.userInfoDic objectForKey:@"userInfo"] objectForKey:@"AccountID"],@"userId", nil] dataBlock:^(NSDictionary *dic) {
            NSString * resultCode = [dic objectForKey:@"resultCode"];
            if ([resultCode isEqualToString:@"0"]) {
                [_mutInfoDic setObject:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"ProfessionalID"];
                [_myInfoView.tableView reloadData];
                [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"修改成功。"];
            }else{
                NSLog(@"修改个人信息参数错误。");
            }
        }];
        _tabBackBtn.hidden = YES;
    }else{
        UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:0];
        switch (indexPath.section) {
            case 0:
            {
                switch (indexPath.row) {
                    case 0:
                    {
                        YXAmendMessageViewController * amendMessageVC = [[YXAmendMessageViewController alloc] init];
                        amendMessageVC.title = @"修改名称";
                        amendMessageVC.tableView = _myInfoView.tableView;
                        amendMessageVC.mutableInfoDic = _mutInfoDic;
                        amendMessageVC.amendType = @"0";
                        [self setHidesBottomBarWhenPushed:YES];
                        [self.navigationController pushViewController:amendMessageVC animated:YES];
                        [self setHidesBottomBarWhenPushed:NO];
                    }
                        break;
                    case 1:
                    {
                        UIButton * blackBtn = (UIButton *)[window viewWithTag:1];
                        if (nil == blackBtn) {
                            CGSize screenSize = [UIScreen mainScreen].bounds.size;
                            blackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                            blackBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
                            blackBtn.tag = 1;
                            blackBtn.frame = [UIScreen mainScreen].bounds;
                            [blackBtn addTarget:self action:@selector(selectSexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                            [window addSubview:blackBtn];

                            UIButton * manBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                            [manBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                            manBtn.bounds = CGRectMake(0, 0, 150, 50);
                            manBtn.center = CGPointMake(screenSize.width/2, screenSize.height/2-25);
                            [manBtn setBackgroundColor:[UIColor whiteColor]];
                            manBtn.tag = 2;
                            manBtn.layer.borderColor = [UIColor grayColor].CGColor;
                            manBtn.layer.borderWidth = .3;
                            [manBtn setTitle:@"男" forState:UIControlStateNormal];
                            [manBtn addTarget:self action:@selector(selectSexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                            [blackBtn addSubview:manBtn];

                            UIButton * womanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                            [womanBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                            womanBtn.bounds = CGRectMake(0, 0, 150, 50);
                            womanBtn.center = CGPointMake(screenSize.width/2, screenSize.height/2+25);
                            womanBtn.backgroundColor = [UIColor whiteColor];
                            womanBtn.tag = 3;
                            womanBtn.layer.borderColor = [UIColor grayColor].CGColor;
                            womanBtn.layer.borderWidth = .3;
                            [womanBtn setTitle:@"女" forState:UIControlStateNormal];
                            [womanBtn addTarget:self action:@selector(selectSexBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                            [blackBtn addSubview:womanBtn];
                        }
                        blackBtn.hidden = NO;
                    }
                        break;
                    case 2:
                    {
                        YXAmendMessageViewController * amendMessageVC = [[YXAmendMessageViewController alloc] init];
                        amendMessageVC.title = @"修改签名";
                        amendMessageVC.tableView = _myInfoView.tableView;
                        amendMessageVC.mutableInfoDic = _mutInfoDic;
                        amendMessageVC.amendType = @"5";
                        [self setHidesBottomBarWhenPushed:YES];
                        [self.navigationController pushViewController:amendMessageVC animated:YES];
                        [self setHidesBottomBarWhenPushed:NO];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            case 1:
            {
                switch (indexPath.row) {
                    case 1:
                    {
                        if (!_tabBackBtn) {
                            _tabBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                            _tabBackBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
                            _tabBackBtn.tag = 6;
                            [_tabBackBtn addTarget:self action:@selector(touchTabBGBtn) forControlEvents:UIControlEventTouchUpInside];
                            _tabBackBtn.frame = [UIScreen mainScreen].bounds;
                            [window addSubview:_tabBackBtn];
                            
                            UITableView * tradeTab = [[UITableView alloc] initWithFrame:CGRectMake(50, 50, 220, ([UIScreen mainScreen].bounds.size.height - 100)) style:UITableViewStylePlain];
                            tradeTab.tag = 10010;
                            tradeTab.delegate = self;
                            tradeTab.dataSource = self;
                            [_tabBackBtn addSubview:tradeTab];
                        }
                        _tabBackBtn.hidden = NO;
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            case 2:
            {
                switch (indexPath.row) {
                    case 0:
                    {
                        YXAmendPasswordViewController * amendPasswordVC = [[YXAmendPasswordViewController alloc] init];
                        amendPasswordVC.title = @"修改密码";
                        [self setHidesBottomBarWhenPushed:YES];
                        [self.navigationController pushViewController:amendPasswordVC animated:YES];
                        [self setHidesBottomBarWhenPushed:NO];
                    }
                        break;
                    case 1:
                    {
                        NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                        YXWindowInfo * windowInfo = [YXWindowInfo sharedWindowInfo];
                        [userDefaults removeObjectForKey:windowInfo.userAccount];
                        [userDefaults removeObjectForKey:windowInfo.userPassword];
                        [userDefaults synchronize];
                        
                        UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:0];
                        YXLoginViewController * loginVC = [[YXLoginViewController alloc] init];
                        window.rootViewController = loginVC;
                    }
                        break;
                    case 2:
                    {
                        YXChangeCodeViewController * changeCodeVC = [[YXChangeCodeViewController alloc] init];
                        [self setHidesBottomBarWhenPushed:YES];
                        [self.navigationController pushViewController:changeCodeVC animated:YES];
                        [self setHidesBottomBarWhenPushed:NO];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            default:
                break;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag == 10010) {
        return 1;
    }
    return [_titleArr count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 10010) {
        return [_tradeArr count];
    }
    return [[_titleArr objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * identifier = @"cell";
    if (tableView.tag == 10010) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (nil == cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.textLabel.text = [_tradeArr objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }else{
        YXPersonMessageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (nil == cell) {
            cell = [[YXPersonMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = [[_titleArr objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        cell.rightLab.frame = CGRectMake(125, 10, 160, 20);
        cell.rightLab.text = @"";
        if (indexPath.section == 1 && indexPath.row == 0) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        cell.showImgBtn.bounds = CGRectZero;
        
        switch (indexPath.section) {
            case 0:
            {
                cell.textLabel.textAlignment = NSTextAlignmentLeft;
                switch (indexPath.row) {
                    case 0:
                    {
                        cell.showImgBtn.bounds = CGRectMake(0, 0, 65, 65);
                        [cell.showImgBtn addTarget:self action:@selector(touchShowImgBtn) forControlEvents:UIControlEventTouchUpInside];
                        cell.showImgBtn.backgroundColor = [UIColor redColor];
                        
                        CGSize size = [[_mutInfoDic objectForKey:@"AccountName"] sizeWithFont:[UIFont systemFontOfSize:15]];
                        if (size.width > 160) {
                            size.height = (size.width/160+1)*20;
                        }
                        if (size.height < 65) {
                            cell.rightLab.frame = CGRectMake(125, (65 - size.height + 20)/2, 160, size.height);
                        }else{
                            cell.rightLab.frame = CGRectMake(125, 10, 160, size.height);
                        }
                        cell.rightLab.text = [_mutInfoDic objectForKey:@"AccountName"];
                    }
                        break;
                    case 1:
                    {
                        cell.rightLab.textColor = [UIColor grayColor];
                        if ([[_mutInfoDic objectForKey:@"AccountSex"] isEqualToString:@"0"]) {
                            cell.rightLab.text = @"女";
                        }else{
                            cell.rightLab.text = @"男";
                        }
                    }
                        break;
                    case 2:
                    {
                        CGSize size = [[_mutInfoDic objectForKey:@"AccountRemark"] sizeWithFont:[UIFont systemFontOfSize:15]];
                        if (size.width > 160) {
                            size.height = (size.width/160+1)*20;
                        }
                        cell.rightLab.frame = CGRectMake(125, 10, 160, size.height);
                        cell.rightLab.text = [_mutInfoDic objectForKey:@"AccountRemark"];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            case 1:
            {
                cell.textLabel.textAlignment = NSTextAlignmentLeft;
                switch (indexPath.row) {
                    case 0:
                    {
                        CGSize size = [[_mutInfoDic objectForKey:@"CompanyName"] sizeWithFont:[UIFont systemFontOfSize:15]];
                        if (size.width > 160) {
                            size.height = (size.width/160+1)*20;
                        }
                        cell.rightLab.frame = CGRectMake(125, 10, 160, size.height);
                        cell.rightLab.text = [_mutInfoDic objectForKey:@"CompanyName"];
                    }
                        break;
                    case 1:
                    {
                        int professionalID = [[_mutInfoDic objectForKey:@"ProfessionalID"] intValue];
                        cell.rightLab.textColor = [UIColor grayColor];
                        cell.rightLab.text = [_professionalsArr objectAtIndex:professionalID];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            case 2:
            {
                cell.textLabel.textAlignment = NSTextAlignmentCenter;
            }
                break;
            default:
                break;
        }
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

#pragma mark - UIButtonsClick
- (void)touchSetBtn
{
    YXSetViewController * setVC = [[YXSetViewController alloc] init];
    [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:setVC animated:YES];
    [self setHidesBottomBarWhenPushed:NO];
}

- (void)touchTabBGBtn
{
    _tabBackBtn.hidden = YES;
}

- (void)selectSexBtnClick:(UIButton *)btn
{
    UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    UIButton * blackBtn = (UIButton *)[window viewWithTag:1];
    blackBtn.hidden = YES;
    switch (btn.tag) {
        case 2:
        {
            if (userSex[1]) {
                blackBtn.hidden = YES;
                return;
            }
            [self sendAmendMessageRequestWithType:@"1" parameter:@"1"];
        }
            break;
        case 3:
        {
            if (userSex[0]) {
                blackBtn.hidden = YES;
                return;
            }
            [self sendAmendMessageRequestWithType:@"1" parameter:@"0"];
        }

        default:
            break;
    }
}

- (void)sendAmendMessageRequestWithType:(NSString *)type parameter:(NSString *)parameter
{
    YXWindowInfo * windowInfo = [YXWindowInfo sharedWindowInfo];
    [NSURLConnection sendRequestWithHeadStr:windowInfo.requestUrlStr headValue:[windowInfo.userInfoDic objectForKey:@"token"] serviceToken:nil text:[NSDictionary dictionaryWithObjectsAndKeys:@"updateUserInfo",@"type",type,@"editType",parameter,@"parameter",[[windowInfo.userInfoDic objectForKey:@"userInfo"] objectForKey:@"AccountID"],@"userId", nil] dataBlock:^(NSDictionary *dic) {
        NSString * resultCode = [dic objectForKey:@"resultCode"];
        if ([resultCode isEqualToString:@"0"]) {
            if (userSex[0]) {
                userSex[0] = NO;
                userSex[1] = YES;
                [_mutInfoDic setObject:@"1" forKey:@"AccountSex"];
            }else{
                userSex[0] = YES;
                userSex[1] = NO;
                [_mutInfoDic setObject:@"0" forKey:@"AccountSex"];
            }
            [_myInfoView.tableView reloadData];
            [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"修改成功。"];
        }else{
            NSLog(@"修改个人信息参数错误。");
        }
    }];
}

- (void)touchShowImgBtn
{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
